package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"sys-manager/models"
)

func ROleNode(c *gin.Context) {
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.RoleNode{
		Nid: nid,
		Rid: rid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "添加成功",
	})
	return
}

func RoleList(c *gin.Context) {
	rid := c.Query("rid")
	var news []models.Node
	/*
			SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	models.DB.Table("nodes").
		Joins(" LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where(" role_nodes.rid = ?", rid).
		Debug().
		Find(&news)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": news,
	})
	return

}

func UserList(c *gin.Context) {
	uid := c.Query("uid")

	var news []models.Role
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = user_roles.id
		WHERE
		  user_roles.rid = 1
	*/
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = user_roles.id").
		Where(" user_roles.rid = ?", uid).
		Debug().
		Find(&news)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": news,
	})
	return
}
